import common from "../../../lib/common/common.js";
import puppeteer from "../../../lib/puppeteer/puppeteer.js";
import {
    PLUGIN_PATH,
    createAGroupFolder,
    getGroupPlayerList,
    getPlayerData,
    isGroupExist,
    isPlayerExist,
    storagePlayerData,
    deletePlayerData
} from "../function/function.js";

export class Sm extends plugin {
    constructor() {
        super({
            name: '[Sm]奴隶列表',
            dsc: '奴隶列表',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/](奴隶|群友)市场$/, fnc: 'slaveList' }
            ]
        })
    }

    async slaveList(e) {
        if (!e.isGroup) return e.reply(['该游戏只能在群内使用'])
        const ID = [e.user_id, e.group_id]

        if (!isGroupExist(ID[1])) {
            createAGroupFolder(ID[1])
        }

        if (!isPlayerExist(ID[1], ID[0])) {
            storagePlayerData(ID[1], ID[0], {
                currency: 0,
                slave: [],
                value: 100,
                lastWorkingTime: 0,
                master: ''
            })
        }

        const groupUserList = getGroupPlayerList(ID[1])

        const memberInfoList = Object.fromEntries([...await Bot.pickGroup(ID[1]).getMemberMap()])
        let playerIdList = groupUserList.map(fileName => fileName.replace('.json', ''));
        let playerIdLists = [];
        for (let i = 0; i < playerIdList.length; i += 200) { // 每200个转为2维数组
            let chunk = playerIdList.slice(i, i + 200);
            playerIdLists.push(chunk);
        }

        let msg = ['未出现在市场里的都只值100'], info = []
        for (let i = 0; i < playerIdLists.length; i++) {
            for (let n = 0; n < playerIdLists[i].length; n++) {
                const slaveData = await getPlayerData(ID[1], playerIdLists[i][n])
                if (!memberInfoList[playerIdLists[i][n]]) {
                    deletePlayerData(ID[1], playerIdLists[i][n])
                    continue
                }
                if (!memberInfoList[slaveData['master']]) {
                    deletePlayerData(ID[1], slaveData['master'])
                    slaveData['master'] = ''
                    storagePlayerData(ID[1], playerIdLists[i][n], slaveData)
                }
                info.push({
                    id: playerIdLists[i][n],
                    name: memberInfoList[playerIdLists[i][n]]['nickname'],
                    socialStatus: slaveData['value'],
                    master: !memberInfoList[slaveData['master']] ? '无' : memberInfoList[slaveData['master']]['nickname']
                })
            }
            msg.push(await puppeteer.screenshot('奴隶列表', {
                tplFile: 'plugins/Slave-Market/resources/html/slaveList/index.html',
                filePath: `${PLUGIN_PATH}/resources/`,
                info
            }))
            info = []
        }

        return e.reply(await common.makeForwardMsg(e, msg, '群友市场', true))
    }
}